package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.system.domain.MedPre;
import com.ruoyi.system.service.IMedPreService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.mapper.PrescriptionMapper;
import com.ruoyi.system.domain.Prescription;
import com.ruoyi.system.service.IPrescriptionService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 处方管理Service业务层处理
 *
 * @author yangxp
 * @date 2020-07-31
 */
@Service
public class PrescriptionServiceImpl extends ServiceImpl<PrescriptionMapper, Prescription> implements IPrescriptionService {
	@Resource
	private IMedPreService medPreService;

	@Override
	@Transactional(rollbackFor = BaseException.class)
	public boolean savePrescription(Prescription prescription) {
		String preId = IdUtil.fastSimpleUUID();
		prescription.setPreId(preId);
		List<MedPre> medicineList = prescription.getMedicineList();
		medicineList.forEach(item -> {
			item.setPreId(preId);
			item.setGmtCreate(DateUtil.date());
			item.setGmtModified(DateUtil.date());
		});
		boolean saveBatch = medPreService.saveBatch(medicineList);
		boolean save = this.save(prescription);
		return saveBatch && save;
	}

	@Override
	@Transactional(rollbackFor = BaseException.class)
	public boolean updatePrescription(Prescription prescription) {
		List<MedPre> medicineList = prescription.getMedicineList();
		String preId = prescription.getPreId();
		//删除所有
		medPreService.remove(new QueryWrapper<MedPre>().eq("pre_id", preId));
		medicineList.forEach(item -> {
			item.setPreId(preId);
			item.setGmtCreate(DateUtil.date());
			item.setGmtModified(DateUtil.date());
			medPreService.save(item);
		});
		prescription.setGmtModified(DateUtil.date());
		this.updateById(prescription);
		return true;
	}

	@Override
	@Transactional(rollbackFor = BaseException.class)
	public boolean removePrescription(Long[] ids) {
		List<Long> idList = Arrays.asList(ids);
		idList.forEach(id -> {
			Prescription prescription = this.getById(id);
			String preId = prescription.getPreId();
			medPreService.remove(new QueryWrapper<MedPre>().eq("pre_id", preId));
		});
		this.removeByIds(idList);
		return true;
	}
}
